<template>
  <view class="container">
    <!-- 主过渡内容 -->
    <view class="transition-content">
		<view class="container1">
		    <!-- 地图容器 -->
		    <map 
		      class="map-container"
		      :longitude="longitude"
		      :latitude="latitude"
		      :scale="scale"
		      :markers="markers"
		      :polyline="polyline"
		      :circles="circles"
		      :controls="controls"
		      @markertap="onMarkerTap"
		      @regionchange="onRegionChange"
		      @controltap="onControlTap"
		      @poitap="onPoiTap">
		    </map>
		    
		    <!-- 操作按钮 -->
		    <!-- <view class="action-buttons">
		      <button class="btn" @click="locateMe">定位到我的位置</button>
		      <button class="btn" @click="addMarker">添加标记点</button>
		      <button class="btn" @click="calculateDistance">计算距离</button>
		    </view> -->
		    
		    <!-- 信息提示 -->
		    <!-- <view class="info-panel" v-if="showInfo">
		      <text class="info-title">{{ infoTitle }}</text>
		      <text class="info-content">{{ infoContent }}</text>
		      <button class="close-btn" @click="closeInfo">关闭</button>
		    </view> -->
		  </view>
      <!-- 动态Logo动画 -->
      <view class="logo-container">
        <view class="logo-circle" :style="{ transform: `scale(${logoScale})` }"></view>
        <image 
          class="logo" 
          src="/static/logo.png" 
          :style="{ opacity: logoOpacity, transform: `rotate(${logoRotation}deg)` }"
        />
      </view>
      
      <!-- 进度条 -->
      <view class="progress-bar">
        <view class="progress" :style="{ width: `${progress}%` }"></view>
      </view>
      
      <!-- 提示文案 -->
      <text class="hint-text" :style="{ opacity: textOpacity }">
        {{ hintTexts[currentHintIndex] }}
      </text>
      
      <!-- 加载指示器 -->
      <view class="loader" v-if="showLoader">
        <view class="dot" v-for="(dot, index) in 3" :key="index"></view>
      </view>
    </view>
    
    <!-- 跳过按钮 -->
    <view 
      class="skip-btn" 
      v-if="showSkipButton"
      @click="skipTransition"
    >
      <text>跳过 {{ skipCountdown }}</text>
    </view>
    
    <!-- 背景元素 -->
    <view class="bg-element" v-for="(item, index) in bgElements" :key="index"
      :style="{
        top: `${item.top}px`,
        left: `${item.left}px`,
        width: `${item.size}px`,
        height: `${item.size}px`,
        transform: `rotate(${item.rotation}deg)`,
        backgroundColor: `rgba(255, 255, 255, ${item.opacity})`
      }">
    </view>
  </view>
</template>

<script>
import { getWxInfo,login } from '@/api/login'
export default {
  data() {
    return {
      longitude: 112.945201, // 默认经度（深圳）
      latitude: 22.542821,  // 默认纬度（深圳）
      scale: 16,            // 地图缩放级别
      markers: [],          // 标记点数组
      polyline: [],         // 路线数组
      circles: [],          // 圆形区域数组
      controls: [           // 自定义控件
      ],		
	  myLocation: [],      // 我的位置信息
      // 过渡状态
      progress: 0,
      logoOpacity: 0,
      logoScale: 0.8,
      logoRotation: 0,
      textOpacity: 0,
      skipCountdown: 5,
      showSkipButton: false,
      showLoader: false,
      
      // 提示文案
      hintTexts: [
        "正在为您准备精彩内容...",
        "优化您的体验...",
        "即将完成...",
        "最后一步..."
      ],
      currentHintIndex: 0,
      
      // 背景动画元素
      bgElements: []
    };
  },
  
  onLoad(options) {
    // 初始化页面
    this.initTransition();
    
    // 根据传入参数决定是否显示跳过按钮
    if (options.showSkip !== 'false') {
      setTimeout(() => {
        this.showSkipButton = true;
        this.startCountdown();
      }, 1000);
    }
    
    // 创建背景动画元素
    this.createBackgroundElements();
  },
  
  methods: {
    // 初始化地图
    // initMap() {
    //   // 获取我的位置
    //   this.locateMe();
    // },	  
// 定位到我的位置
    locateMe() {
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.longitude = res.longitude
          this.latitude = res.latitude
		  console.log("longitude"+res.longitude)
		  console.log("latitude"+res.latitude)
          this.myLocation = {
            longitude: res.longitude,
            latitude: res.latitude
          }
        },
        fail: (err) => {
          console.error('获取位置失败:', err)
          this.showInfo = true
          this.infoTitle = '定位失败'
          this.infoContent = '请确保您已授权位置信息并开启GPS'
          
          // 引导用户授权
          if (err.errMsg.indexOf('auth deny') !== -1) {
            setTimeout(() => {
              uni.showModal({
                title: '权限申请',
                content: '需要获取您的位置信息才能正常使用地图功能',
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting()
                  }
                }
              })
            }, 1000)
          }
        }
      })
    },	
    wechatLogin() {
      // 判断是否在微信环境中
      if (typeof wx !== 'undefined' && wx.login) {
        wx.login({
          success: (res) => {
            if (res.code) {
              console.log('登录成功，code为:', res.code)
              // 这里可以将 code 发送到你的服务器
              this.sendCodeToServer(res.code)
              // this.$tab.reLaunch('/pages/index')
            } else {
              console.log('登录失败:', res.errMsg)
            }
          },
          fail: (err) => {
            console.error('wx.login 调用失败:', err)
          }
        })
      } else {
        console.warn('当前环境不支持微信登录')
      }
    },
// 发送 code 到服务器的示例方法
    sendCodeToServer(code) {
        getWxInfo(code).then(res => {
            console.log("getWxInfo =="+res.data.openId);
            this.pwdLogin(res.data.openId)
        });
    },
    async pwdLogin(openId) {
        console.log("openId"+openId)
		this.locateMe();
		var longitude = this.myLocation.longitude;
		var latitude = this.myLocation.latitude;
        this.$store.dispatch('LoginWx', openId,longitude,latitude).then(res => {
            console.log("openId=="+openId)
          this.loginSuccess()
        }).catch(() => {
          if (this.captchaEnabled) {
            this.getCode()
          }
        })
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
        // 设置用户信息
        this.$store.dispatch('GetInfo').then(res => {
          this.$tab.reLaunch('/pages/index')
        })
    },
    // 初始化过渡效果
    initTransition() {
      // 1. Logo入场动画
      setTimeout(() => {
        this.logoOpacity = 1;
        this.logoScale = 1;
        
        // 开始旋转动画
        this.rotateLogo();
      }, 300);
      
      // 2. 进度条动画
      const progressInterval = setInterval(() => {
        if (this.progress < 100) {
          this.progress += 1;
        } else {
          clearInterval(progressInterval);
          this.completeTransition();
        }
      }, 30);
      
      // 3. 提示文本动画
      let hintIndex = 0;
      const hintInterval = setInterval(() => {
        if (hintIndex < this.hintTexts.length) {
          this.textOpacity = 0;
          setTimeout(() => {
            this.currentHintIndex = hintIndex;
            this.textOpacity = 1;
            hintIndex++;
          }, 300);
        } else {
          clearInterval(hintInterval);
        }
      }, 1500);
      
      // 4. 在进度70%时显示加载指示器
      setTimeout(() => {
        this.showLoader = true;
      }, 2000);
    },
    
    // 旋转Logo动画
    rotateLogo() {
      const rotate = () => {
        this.logoRotation += 1;
        // requestAnimationFrame(rotate);
      };
      rotate();
    },
    
    // 跳过倒计时
    startCountdown() {
      const countdownInterval = setInterval(() => {
        if (this.skipCountdown > 1) {
          this.skipCountdown -= 1;
        } else {
          clearInterval(countdownInterval);
          this.skipTransition();
        }
      }, 1000);
    },
    
    // 跳过过渡
    skipTransition() {
      // 这里可以添加跳过动画
      // this.wechatLogin();
      this.pwdLogin("ob9YY0QAggRfiTdbqbNPiZZreAWs");//测试时使用
      // uni.redirectTo({
      //   url: '/pages/index'
      // });
    },
    
    // 完成过渡
    completeTransition() {
      // 完成动画效果
      uni.showToast({
        title: '准备完成！',
        icon: 'success',
        duration: 500
      });
      
      // 跳转到主页面
      setTimeout(() => {
        // this.wechatLogin();
        this.pwdLogin("ob9YY0QAggRfiTdbqbNPiZZreAWs");//测试时使用
        // uni.switchTab({
        //   url: '/pages/index'
        // });
      }, 800);
    },
    
    // 创建背景动画元素
    createBackgroundElements() {
      const screenWidth = uni.getSystemInfoSync().windowWidth;
      const screenHeight = uni.getSystemInfoSync().windowHeight;
      
      for (let i = 0; i < 12; i++) {
        this.bgElements.push({
          top: Math.random() * screenHeight,
          left: Math.random() * screenWidth,
          size: 10 + Math.random() * 60,
          rotation: Math.random() * 360,
          opacity: 0.05 + Math.random() * 0.1
        });
      }
      
      // 动画背景元素
      // this.animateBackground();
    },
    
    // 动画背景元素
    // animateBackground() {
    //   const animate = () => {
    //     this.bgElements = this.bgElements.map(el => {
    //       return {
    //         ...el,
    //         rotation: el.rotation + 0.2,
    //         opacity: 0.05 + Math.abs(Math.sin(Date.now() / 1000 + el.left)) * 0.1
    //       };
    //     });
    //     // requestAnimationFrame(animate);
    //   };
    //   animate();
    // }
  }
};
</script>

<style lang="scss" scoped>
.map-container{
	display: none;
}
.container1 {
  display:none;
  width: 1vh;
  height: 1vh;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}	
	
.container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.transition-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
}

.logo-container {
  position: relative;
  width: 150px;
  height: 150px;
  margin-bottom: 40px;
}

.logo-circle {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  transition: transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.logo {
  width: 100%;
  height: 100%;
  transition: opacity 0.8s ease, transform 0.2s linear;
}

.progress-bar {
  width: 280px;
  height: 6px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 30px;
}

.progress {
  height: 100%;
  background: #ffffff;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.hint-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  margin-bottom: 25px;
  text-align: center;
  transition: opacity 0.3s ease;
}

.loader {
  display: flex;
  justify-content: center;
  align-items: center;
  
  .dot {
    width: 10px;
    height: 10px;
    background: #fff;
    border-radius: 50%;
    margin: 0 5px;
    opacity: 0.6;
    
    &:nth-child(1) {
      animation: loader 1.2s infinite ease-in-out;
    }
    &:nth-child(2) {
      animation: loader 1.2s infinite ease-in-out 0.2s;
    }
    &:nth-child(3) {
      animation: loader 1.2s infinite ease-in-out 0.4s;
    }
  }
}

@keyframes loader {
  0%, 100% { transform: scale(0.8); opacity: 0.6; }
  50% { transform: scale(1.2); opacity: 1; }
}

.skip-btn {
  position: absolute;
  bottom: 40px;
  padding: 8px 20px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
  z-index: 20;
  transition: all 0.3s;
  
  &:active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0.95);
  }
}

.bg-element {
  position: absolute;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.1);
}
</style> -->